<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'

import { computed, h, ref } from 'vue'
import { Page, useVbenModal } from '@vben/common-ui'
import { Button, message, Tag, Popconfirm, Spin } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import { getRevicedRecordList, doRevicedRecordAgainst, doRevicedRecordApproval, doRevicedRecordDelete, exportExpiredData } from '#/api/revicedRecord'
import { getSupplyList, getAdminList } from '#/api/common'
import { useDebounceFn } from '@vueuse/core'
import RevicedLog from './modules/revicedLog.vue'
import Form from './modules/form.vue'

import { AntPlusOutlined, AntDeleteOutlined, AntCheckOutlined, AntCloseOutlined } from '@vben/icons'
import dayjs from 'dayjs'

interface RowType {
  [key: string]: any
}

const selectedRows = ref<RowType[]>([])
const formData = ref<any>({})
const keyword = ref({
  admin_id: '',
  supply_id: '',
})
const fetching = ref({
  admin_id: false,
  supply_id: false,
})

const fetchAdminIdOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: !keyword ? formData.value?.admin_id : '',
    select: true,
  })

  return list.map((item) => ({
    label: item.realname,
    value: item.id,
  }))
}

const fetchSupplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getSupplyList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'supply.id',
    initValue: !keyword ? formData.value?.supply_id : '',
    select: true,
  })

  return list.map((item) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

// 获取选中行的ID数组
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.record_id)
}

// 审核按钮判断
const isDisabledApproval = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.posted >= 1)
})

// 反审按钮判断
const isDisabledAgainst = computed(() => {
  return selectedRows.value.length <= 0 || selectedRows.value.some((row: any) => row.posted === 0)
})

// 默认排序
const defaultSort: { field: string; order: '' | 'asc' | 'desc' | null } = {
  field: 'record_id',
  order: 'desc',
}

const fetchData = async () => {
  gridApi.reload()
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Input',
      fieldName: 'record_sn',
      label: '收料单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'purchase*purchase_sn',
      label: '手工单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'purchase*caigou_id',
      label: '采购单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Input',
      fieldName: 'material_name',
      label: '物料名称',
      operator: 'false',
      componentProps: {
        allowClear: true,
      },
    },
    {
      component: 'Select',
      fieldName: 'post_time',
      label: '审核状态',
      operator: '=',
      componentProps: {
        allowClear: true,
        options: [
          { label: '未审核', value: '0' },
          { label: '已审核', value: '1' },
        ],
        placeholder: '请选择',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'record_date',
      label: '单据日期',
      operator: 'RANGE',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchAdminIdOptions,
          // 禁止本地过滤
          filterOption: false,
          // 如果正在获取数据，使用插槽显示一个loading
          notFoundContent: fetching.value.admin_id ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword.value.admin_id = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword.value.admin_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          //  mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value.admin_id = ''
          },
        }
      },
      fieldName: 'admin*id',
      label: '操作人',
      operator: '=',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value.admin_id ? h(Spin) : undefined,
        }
      },
    },

    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchSupplyOptions,
          // 禁止本地过滤
          filterOption: false,
          // 如果正在获取数据，使用插槽显示一个loading
          notFoundContent: fetching.value.supply_id ? undefined : null,
          // 搜索词变化时记录下来， 使用useDebounceFn防抖。
          onSearch: useDebounceFn((value: string) => {
            keyword.value.supply_id = value
          }, 300),
          // 远程搜索参数。当搜索词变化时，params也会更新
          params: {
            keyword: keyword.value.supply_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          //  mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            if (open) keyword.value.supply_id = ''
          },
        }
      },
      fieldName: 'supply*id',
      label: '供应商',
      operator: '=',
      renderComponentContent: () => {
        return {
          notFoundContent: fetching.value.supply_id ? h(Spin) : undefined,
        }
      },
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'record_id',
    // isCurrent: true,
    isHover: true,
  },
  columnConfig: {
    useKey: true,
  },
  // cellConfig: { height: 60 },
  rowStyle({ row, rowIndex }) {
    if (row.posted === 0) {
      return {
        color: 'red',
      }
    }
  },
  columns: [
    { type: 'checkbox', width: 50, fixed: 'left' },
    { field: 'record_sn', width: 150, title: '收料单号', fixed: 'left' },
    { field: 'purchase.purchase_sn', width: 150, title: '手工单号' },
    { field: 'purchase.caigou_id', width: 150, title: '采购单号' },
    { field: 'total_num', width: 100, title: '总数量' },
    { field: 'total_price', width: 100, title: '总价' },
    {
      field: 'admin.realname',
      width: 120,
      title: '创建人',
    },
    {
      field: 'supply_info',
      width: 150,
      title: '供应商',
      slots: { default: 'supplyInfo' },
    },
    {
      field: 'warehouse_info',
      width: 150,
      title: '仓库',
      slots: { default: 'warehouseInfo' },
    },
    {
      field: 'postStatus',
      width: 100,
      title: '审核状态',
      slots: { default: 'postStatus' },
    },
    { field: 'created_at', width: 160, title: '录入时间' },
    {
      field: 'post_time',
      width: 160,
      title: '审核时间',
      formatter: ({ cellValue }) => {
        if (cellValue && Number(cellValue) > 0) {
          return dayjs(Number(cellValue) * 1000).format('YYYY-MM-DD HH:mm:ss')
        }
        return '-'
      },
    },
    { field: 'record_date', width: 160, title: '单据日期' },
    {
      field: 'operation',
      fixed: 'right',
      slots: { default: 'operation' },
      title: '操作',
      width: 170,
    },
  ],
  exportConfig: {},
  height: 'auto',
  keepSource: true,
  pagerConfig: {
    pageSize: 20,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page, sort }, formValues) => {
        const search = await gridApi.formApi.getFiltersValues()
        // 这里需要根据实际API调整
        const res = await getRevicedRecordList({
          page: page.currentPage,
          limit: page.pageSize,
          search,
          order: sort.field && sort.order ? `${sort.field},${sort.order}` : `${defaultSort.field},${defaultSort.order}`,
        })

        return {
          items: res.list,
          total: res.total,
        }
      },
    },
    sort: true,
  },
  sortConfig: {
    defaultSort,
    remote: true,
  },
  toolbarConfig: {
    custom: true,
    export: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'reviced_record_list',
  customConfig: {
    storage: true,
  },
}

// 获取审核状态标签颜色
const getPostStatusColor = (postTime: string | number) => {
  return postTime && Number(postTime) > 0 ? 'success' : 'warning'
}

// 获取审核状态文本
const getPostStatusText = (postTime: string | number) => {
  return postTime && Number(postTime) > 0 ? '已审核' : '未审核'
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    }
  },
})

// 导出功能
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    await exportExpiredData({ search })
  } catch (e) {
    message.error('导出失败')
  } finally {
    hide()
  }
}

// 事件处理
const handleshowFormData = (row: RowType) => {
  FormModalApi.setData({
    info: row,
  }).open()
}
const [FormModal, FormModalApi] = useVbenModal({
  connectedComponent: Form,
})

// 事件处理
const handleshowRecordData = (row: RowType) => {
  RevicedLogModalApi.setData({
    info: row,
  }).open()
}
const [RevicedLogModal, RevicedLogModalApi] = useVbenModal({
  connectedComponent: RevicedLog,
})

const handleDelete = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要删除的数据')
    return
  }
  const hideLoading = message.loading({
    content: '删除',
    duration: 0,
    key: 'action_process_msg',
  })

  doRevicedRecordDelete({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '删除成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理审核操作
const handleApproval = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要审核的数据')
    return
  }
  const hideLoading = message.loading({
    content: '审核',
    duration: 0,
    key: 'action_process_msg',
  })

  doRevicedRecordApproval({ ids: getSelectionIds(), is_confirm_ware: 0 })
    .then(() => {
      message.success({
        content: '审核成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}

// 处理反审操作
const handleAgainst = () => {
  if (selectedRows.value.length === 0) {
    message.warning('请先选择要反审的数据')
    return
  }

  const hideLoading = message.loading({
    content: '反审',
    duration: 0,
    key: 'action_process_msg',
  })

  doRevicedRecordAgainst({ ids: getSelectionIds() })
    .then(() => {
      message.success({
        content: '反审成功',
        key: 'action_process_msg',
      })
      gridApi.query()
    })
    .catch(() => {
      hideLoading()
    })
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <Button class="mr-2" type="primary" @click="handleshowFormData({})">
          <AntPlusOutlined />
          新建
        </Button>
        <Popconfirm
          :disabled="isDisabledApproval"
          title="确认删除"
          :description="`确定要删除选中的 ${selectedRows.length} 条数据吗？此操作不可恢复。`"
          ok-text="确认"
          cancel-text="取消"
          @confirm="handleDelete"
          @cancel="() => {}"
        >
          <Button class="mr-2" type="primary" danger :disabled="isDisabledApproval">
            <AntDeleteOutlined />
            删除
          </Button>
        </Popconfirm>

        <Popconfirm :disabled="isDisabledApproval" title="确认审核" :description="`确定要审核选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleApproval" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledApproval ? 'ant-btn-disabled' : 'bg-[#24b916] text-white hover:opacity-75']" :disabled="isDisabledApproval">
            <AntCheckOutlined />
            审核
          </Button>
        </Popconfirm>
        <Popconfirm :disabled="isDisabledAgainst" title="确认反审" :description="`确定要反审选中的 ${selectedRows.length} 条数据吗？`" ok-text="确认" cancel-text="取消" @confirm="handleAgainst" @cancel="() => {}">
          <Button type="ghost" :class="['mr-2', isDisabledAgainst ? 'ant-btn-disabled' : 'bg-[#f56c6c] text-white hover:opacity-75']" :disabled="isDisabledAgainst">
            <AntCloseOutlined />
            反审
          </Button>
        </Popconfirm>
        <Button type="ghost" class="mr-2 bg-[#e6a23c] text-white hover:opacity-75" @click="handleExport">导出</Button>
      </template>

      <template #supplyInfo="{ row }">
        <div>{{ row.supply?.SupplyCode }}/{{ row.supply?.SupplyNa }}</div>
      </template>

      <template #warehouseInfo="{ row }">
        <div>{{ row.warehouse?.warehouse_code }}/{{ row.warehouse?.warehouse_name }}</div>
      </template>

      <template #postStatus="{ row }">
        <Tag :color="getPostStatusColor(row.post_time)">
          {{ getPostStatusText(row.post_time) }}
        </Tag>
      </template>

      <template #operation="{ row }">
        <Button type="ghost" class="mr-2 bg-[#e6a23c] text-white hover:opacity-75" size="small" @click.stop="handleshowRecordData(row)">收料记录</Button>
        <Button class="mr-2" type="primary" size="small" @click.stop="handleshowFormData(row)">编辑</Button>
      </template>
    </Grid>
    <RevicedLogModal />
    <FormModal @fetch-data="fetchData" />
  </Page>
</template>
